
import * as THREE from "three";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader";
import { OrbitControls } from "three/addons/controls/OrbitControls";

const initMethod = {
  initThree:(canvas) => {
    console.log('初始化three======》');
    // 1.创建场景
    const scene = new THREE.Scene();
    // 添加辅助线
    // let axesHelper = new THREE.AxesHelper( 150 );
    // scene.add(axesHelper);


    // scene.background = 0x0000ff;
    scene.background = new THREE.Color("white");
    // 2.创建相机
    const camera = new THREE.PerspectiveCamera( 100, window.innerWidth / window.innerHeight, 1, 200 );
    // 2.1设置相机的初始位置
    // camera.position.z = 5;
    camera.position.set(0, 0, 5);
    // 3.设置渲染空间大小
    const renderer = new THREE.WebGLRenderer({antialias: true, canvas});
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( canvas );

    // 加载荔枝模型
    const loader = new GLTFLoader();
    loader.load( '/guiwei/scene.gltf', function ( gltf ) {
      let model = gltf.scene;
      model.traverse((o) => {
        //将图片作为纹理加载
        let explosionTexture = new THREE.TextureLoader().load(
          '/guiwei/textures/material_baseColor.jpeg'
        )
        //调整纹理图的方向
        explosionTexture.flipY = false
        //将纹理图生成基础网格材质(MeshBasicMaterial)
        const material = new THREE.MeshBasicMaterial({
          map: explosionTexture,
        })
        //给模型每部分上材质
        o.material = material
      })
      // scene.add(model)
    }, undefined, function ( error ) {
      console.error( error );
    } );

    // 创建立方体
    const geometry = new THREE.BoxGeometry( 1, 1, 1 );
    const material = new THREE.MeshBasicMaterial( { color: 3099590 } );
    const cube = new THREE.Mesh( geometry, material );
    scene.add( cube );

    function resizeRendererToDisplaySize(renderer) {
      const canvas = renderer.domElement
      var width = window.innerWidth
      var height = window.innerHeight
      var canvasPixelWidth = canvas.width / window.devicePixelRatio
      var canvasPixelHeight = canvas.height / window.devicePixelRatio

      const needResize = canvasPixelWidth !== width || canvasPixelHeight !== height
      if (needResize) {
        renderer.setSize(width, height, false)
      }
      return needResize
    }


    // 添加轨道控制
    const controls = new OrbitControls( camera, renderer.domElement );
    // 设置阻尼
    controls.enableDamping = true
    controls.dampingFactor = 0.1;

    function animate() {
      controls.update();
      requestAnimationFrame( animate );
      renderer.render( scene, camera );

      // if (resizeRendererToDisplaySize(renderer)) {
      //   const canvas = renderer.domElement
      //   camera.aspect = canvas.clientWidth / canvas.clientHeight
      //   camera.updateProjectionMatrix()
      // }
    }
    animate();
  }
};
export default initMethod;